<template>
  <div class="app-container">

    <el-tabs type="border-card" style="box-shadow: none; border: none;">
      <el-tab-pane label="系统参数设置">
        <el-table
            :data="systemList"
            border
            style="width: 100%"
            v-loading="loading"
            empty-text="暂无参数数据">
          <el-table-column
              prop="name"
              label="参数名称"
              width="180"
              align="center"
          >
          </el-table-column>

          <!-- 参数值列 -->
          <el-table-column
              prop="value"
              label="参数值"
              align="center"
          >
            <template slot-scope="scope">
              <!-- 文本类型显示输入框 -->
              <el-input
                  v-if="scope.row.type === 0"
                  v-model="scope.row.value"
                  size="small"
                  placeholder="请输入参数值"
                  @keyup.enter.native="handleEdit(scope.row)">
              </el-input>
              <!-- 开关类型不显示任何内容 -->
              <span v-else> </span>
            </template>
          </el-table-column>

          <!-- 操作列 -->
          <el-table-column
              label="操作"
              width="220"
              align="center">
            <template slot-scope="scope">
              <!-- 文本类型操作：修改 + 启用/禁用 -->
              <template v-if="scope.row.type === 0">
                <el-button
                    size="mini"
                    type="success"
                    @click="handleEdit(scope.row)">
                  确认修改
                </el-button>
                <el-button
                    size="mini"
                    :type="scope.row.state == 1 ? 'danger' : 'success'"
                    @click="handleEditState(scope.row)">
                  {{ scope.row.state == 1 ? '禁用' : '启用' }}
                </el-button>
              </template>

              <!-- 开关类型操作：只显示开关 -->
              <el-switch
                  v-else
                  v-model="scope.row.value"
                  :active-value="'1'"
                  :inactive-value="'0'"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  @change="handleEditState(scope.row)">
              </el-switch>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 新增参数弹窗 -->
    <el-dialog
        title="新增系统参数"
        :visible.sync="dialogVisible"
        width="500px"
        :close-on-click-modal="false"
        class="patient-dialog"
        @closed="addEmptyForm">
      <el-form
          :model="addForm"
          size="mini"
          label-width="100px"
          :rules="rules"
          ref="addForm">
        <el-form-item label="参数名称:" prop="name">
          <el-input
              v-model="addForm.name"
              placeholder="请输入参数名称"
              @input="generateParamCode">
          </el-input>
        </el-form-item>
        <el-form-item label="参数拼音:" prop="param">
          <el-input
              disabled
              v-model="addForm.param"
              placeholder="自动生成">
          </el-input>
        </el-form-item>
        <el-form-item label="参数值:" prop="value">
          <el-input
              v-model="addForm.value"
              placeholder="请输入参数值">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="submitAddForm" size="mini">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getSystemList, saveSystemData, updateSystemData} from "@/api/systemParameter/systemParameter"
import {pinyin} from "pinyin-pro"
import {withLoading} from "@/untils/loading";

export default {
  data() {
    return {
      dialogVisible: false,
      loading: false,
      systemList: [],
      addForm: {
        name: '',
        param: '',
        value: '',
      },
      rules: {
        name: [{required: true, message: '请输入参数名称', trigger: 'blur'}],
        param: [{required: true, message: '请输入拼音缩写', trigger: 'blur'}],
        value: [{required: true, message: '请输入参数值', trigger: 'blur'}]
      }
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    addEmptyForm() {
      this.addForm = {name: '', param: '', value: ''}
      this.$refs.addForm && this.$refs.addForm.resetFields()
    },

    generateParamCode() {
      if (!this.addForm.name) {
        this.addForm.param = ''
        return
      }
      let code = this.addForm.name.replace(/\s+/g, '')
      this.addForm.param = pinyin(code, {pattern: 'first', toneType: 'none', separator: ''}).toLowerCase()
    },

    async loadData() {
      this.loading = true
      try {
        const res = await getSystemList()
        this.systemList = res.data || []
      } catch (error) {
        console.error(error)
        this.$message.error('获取参数列表失败')
      } finally {
        this.loading = false
      }
    },

    submitAddForm() {
      this.$refs.addForm.validate(async (valid) => {
        if (!valid) return

        try {
          const res = await saveSystemData(this.addForm)
          if (res.code) {
            this.$message.success('添加参数成功!')
            this.dialogVisible = false
            await this.loadData()
          } else {
            this.$message.error(res.message || '添加参数失败!')
          }
        } catch (error) {
          console.error(error)
          this.$message.error('添加参数失败!')
        }
      })
    },

    async handleEditState(item) {
      if (item.type === 0) {
        item.state = item.state === 1 ? 0 : 1
      }
      console.log(item,'valuevaluevalue')
      await this.handleEdit(item)
    },

    async handleEdit(item) {
      const res = await updateSystemData(item)
      if (res.code === 200) {
        await this.loadData()
      } else {
        this.$message.error(res.message)
      }
      /*await withLoading(this, '数据处理中...')(async () => {

      });*/
    },
    getColumnWidth(label, prop, tableData) {
      const minWidth = 80;
      const padding = 30; // 增加边距缓冲
      const contentList = tableData.map(item => item?.[prop] ?? '');

      // 计算所有内容宽度（包括表头）
      const widths = [...contentList, label].map(text => {
        const str = String(text || '');
        return this.getTextWidth(str) + padding;
      });

      return Math.max(minWidth, ...widths);
    },

    // 精确计算文本宽度（使用Canvas）
    getTextWidth(text, fontSize = 14) {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      ctx.font = `${fontSize}px Microsoft YaHei`;
      return ctx.measureText(text).width;
    },

    labelHead(h, {column, $index}) {
      let l = column.label.length;
      let f = 12;
      column.minWidth = f * (l + 5); //加上一个文字长度
      return h("div", {class: "table-head", style: {width: "100%"}}, [
        column.label,
      ]);
    },
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.box-card {
  min-height: calc(100vh - 90px);
}

.settings-title {
  display: inline-block;
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.add-param-btn {
  float: right;
  padding: 8px 15px;
}

.el-table {
  margin-top: 20px;
}

.el-tag {
  min-width: 60px;
}

.dialog-footer {
  text-align: right;
}
</style>